package com.zqxq.lottery.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.zqxq.common.constant.Result;
import com.zqxq.common.utils.BigDecimalUtils;
import com.zqxq.common.utils.StrUtils;
import com.zqxq.lottery.api.config.WechatConfig;
import com.zqxq.lottery.api.feign.LotteryServerFeignClient;
import com.zqxq.lottery.api.utils.WechatUtil;
import com.zqxq.lottery.entity.bo.order.TradeInfoBO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;
@Api(value = "微信回调API接口",tags = "微信回调API接口")
@Controller
@RequestMapping("/wechatNotify")
@Slf4j
public class WeChatNotifyController {
    @Autowired
    private LotteryServerFeignClient lotteryServerFeignClient;
    @Autowired
    private WechatConfig wechatConfig;

    @ResponseBody
    @RequestMapping(value = "payNotifyUrl")
    @ApiOperation(value="微信 异步回调地址", notes="微信 异步回调地址")
    public String payNotifyUrl(HttpServletRequest request){
        String resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
        boolean resFlag = true;
        try{
            InputStream inputStream;
            StringBuffer sb = new StringBuffer();
            inputStream = request.getInputStream();
            String s ;
            BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            while ((s = in.readLine()) != null){
                sb.append(s);
            }
            in.close();
            inputStream.close();
            Map<String, String> m = new HashMap<String, String>();
            m = WechatUtil.doXMLParse(sb.toString());
            SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
            Iterator it = m.keySet().iterator();
            while (it.hasNext()) {
                String parameter = (String) it.next();
                String parameterValue = m.get(parameter);
                String v = "";
                if(null != parameterValue) {
                    v = parameterValue.trim();
                }
                packageParams.put(parameter, v);
            }
            String key = wechatConfig.getKey();
            if(WechatUtil.isTenpaySign("UTF-8", packageParams,key)) {
                if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
                    long userId = 0;
                    int type = 0;
                    Long couponId = null;
                    BigDecimal balance = BigDecimal.ZERO;
                    System.out.println("packageParams:"+packageParams);
                    String passback_params = String.valueOf(packageParams.get("attach"));
                    passback_params = URLDecoder.decode(passback_params, "utf-8");
                    String[] arr = passback_params.split(",");
                    type = Integer.parseInt(arr[0]);
                    userId = Long.parseLong(arr[1]);
                    if (StrUtils.isNotEmpty(arr[2]) && !"null".equals(arr[2].toLowerCase())){
                        couponId = Long.parseLong(arr[2]);
                    }
                    if (StrUtils.isNotEmpty(arr[3]) && !"null".equals(arr[3].toLowerCase())){
                        balance = new BigDecimal(arr[3]);
                    }
                    String total_fee = String.valueOf(packageParams.get("total_fee"));
                    String out_trade_no = String.valueOf(packageParams.get("out_trade_no"));
                    String openid = String.valueOf(packageParams.get("openid"));
                    String result_code = String.valueOf(packageParams.get("result_code"));
                    TradeInfoBO bo = new TradeInfoBO();
                    bo.setUserId(userId);
                    bo.setTradeNo(out_trade_no);
                    bo.setTradeWay(2);
                    bo.setTradeType(type);
                    bo.setOrderId(Long.parseLong(out_trade_no));
                    bo.setResult(result_code);
                    bo.setData(JSONObject.toJSONString(packageParams));
                    Result rs1 = lotteryServerFeignClient.insertTradeInfo(bo);
                    if(!rs1.success()){
                        resFlag = false;
                    }
                    if(type == 0){
                        Result rs = lotteryServerFeignClient.recharge(userId, new BigDecimal(total_fee).divide(new BigDecimal(100)), 6, openid, Long.parseLong(out_trade_no));
                        if(!rs.success()){
                            resFlag = false;
                        }
                    } else if(type == 1){
                        Result rs = lotteryServerFeignClient.wechatConsume(userId, new BigDecimal(total_fee).divide(new BigDecimal(100)), Long.parseLong(out_trade_no), openid,couponId,balance);
                        if(!rs.success()){
                            resFlag = false;
                        }
                    }
                } else {
                    resFlag = false;
                }
            } else{
                log.error("通知签名验证失败");
                resFlag = false;
            }
        } catch (Exception e) {
            log.error("wechat  alipayNotity is error", e);
            resFlag = false;
        }
        if(resFlag==false){
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
        }
        return resXml;
    }

}
